package org.example.DesignPatterns.Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description:
 * @author: farprt
 * @create: 2022-08-14 02:02
 **/
public class SimpleJDKDynamicProxyDemo {
    interface IService{
        public void sayHello();
    }

    static class RealService implements IService{
        @Override
        public void sayHello() {
            System.out.println("hello");
        }
    }

    //对代理接口所有方法的调用都会转给该方法
    static class SimpleInvocationHandler implements InvocationHandler{

        private Object realObj;
        public SimpleInvocationHandler(Object realObj){
            this.realObj=realObj;
        }

        //proxy代理对象本身，method正在被调用的方法，args方法参数
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("entering"+method.getName());
            Object result=method.invoke(realObj,args);
            System.out.println("leaving"+method.getName());
            return result;
        }

    }

    public static void main(String[] args) {
        IService realService=new RealService();
        IService proxyService= (IService) Proxy.newProxyInstance(IService.class.getClassLoader(),new Class[]{IService.class},new SimpleInvocationHandler(realService));
        proxyService.sayHello();

    }

}